package com.java1234.controller;

import com.java1234.entity.R;
import com.java1234.entity.Task;
import com.java1234.service.TasksService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class TasksController {
    @Autowired
    private TasksService tasksService;


    /**
     * 查询所有今日任务
     * @return R
     */
    @GetMapping("/tasks")
    public R selectTodayTasks(){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("tasksList", tasksService.selectTodayTasks(username));
        return R.ok(resultMap);
    }

    /**
     * 查询指定id的任务
     * @param id
     * @return
     */
    @GetMapping("/tasks/{id}")
    public R selectTaskById(@PathVariable("id") Integer id){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        return R.ok(tasksService.selectTaskById(id,username));
    }

    /**
     * 新增任务
     * @param task
     * @return
     */
    @PostMapping("/tasks")
    public R insertTask(@RequestBody Task task){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        return R.ok(tasksService.insertTask(task,username));
    }

    /**
     * 修改任务
     */
    @PutMapping("/tasks/{id}")
    public R updateTask(@RequestBody Task task,@PathVariable("id") Integer id){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        return R.ok(tasksService.updateTask(task, id,username));
    }

    /**
     * 更新任务状态
     */
    @PutMapping("/tasks/{id}/{status}")
    public R updateTaskStatus(@PathVariable("status") Integer status,@PathVariable("id") Integer id){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        return R.ok(tasksService.updateTaskStatus(status,id,username));
    }

    /**
     * 删除任务
     * @param id
     * @return
     */
    @DeleteMapping("/tasks/{id}")
    public R deleteTask(@PathVariable("id") Integer id){
        String username = ((Authentication) SecurityContextHolder.getContext().getAuthentication()).getName();
        return R.ok(tasksService.deleteTask(id,username));
    }
}
